from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, classification_report

# 加载数据集
newsgroups = fetch_20newsgroups(subset='all', remove=('headers', 'footers', 'quotes'))

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(newsgroups.data, newsgroups.target, test_size=0.2, random_state=42)

# 特征提取（使用词袋模型）
vectorizer = CountVectorizer(stop_words='english', max_features=5000)
X_train_vec = vectorizer.fit_transform(X_train)
X_test_vec = vectorizer.transform(X_test)

# 训练朴素贝叶斯分类器
naive_bayes = MultinomialNB()
naive_bayes.fit(X_train_vec, y_train)

# 在测试集上进行预测
y_pred = naive_bayes.predict(X_test_vec)

# 评估模型性能
accuracy = accuracy_score(y_test, y_pred)
print(f'准确率：{accuracy:.2%}')
print('\n分类报告：')
print(classification_report(y_test, y_pred, target_names=newsgroups.target_names))
